<template>
  <div>
    <div class="ccui-navigation" ref="noPrintTop">
      <!-- 面包屑 -->
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
          >结算管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
          >物资结算管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          v-if="$route.query.type === 'approval'"
          :to="{ path: '/settlement-management/settlementApproval' }"
          >结算单审批
        </el-breadcrumb-item>
        <el-breadcrumb-item v-else :to="{ path: breadUrl }"
          >结算单维护
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb"
            >查看 {{ settlementForm.settlementName }}</span
          >
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div v-if="isTrue" class="detail-info">
        <div class="detail-info-el-Label">
          <el-label :type="approving" v-if="approvingStatus"></el-label>
        </div>
        <div class="ccui-app-container-detail-body">
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            class="el-tabs__customize"
          >
            <el-tab-pane label="基本信息" name="first">
              <baseInfoCheck
                ref="bassettlement-checkeInfo"
                :detail="detailInfo"
                :myId="myId"
                :settlement-form="settlementForm"
              />
            </el-tab-pane>

            <el-tab-pane label="结算单明细" name="second">
              <keep-alive>
                <financeInfoCheck
                  ref="financeInfo"
                  :settlementList="settlementList"
                  :detail="detailInfo"
                />
              </keep-alive>
            </el-tab-pane>

            <el-tab-pane label="验收单明细" name="third">
              <keep-alive>
                <purchaseListCheck
                  ref="purchaseList"
                  :settlementList="settlementList"
                  :detail="detailInfo"
                />
              </keep-alive>
            </el-tab-pane>

            <el-tab-pane label="附件" name="fouth" class="file-group">
              <fileInfo
                ref="fileInfo"
                v-model="fileList"
                state="detail"
              ></fileInfo>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!--右边审批状态-->
      <approval-read-record
        v-if="isTrue"
        :approvalRecordData="activities"
      ></approval-read-record>
    </div>

    <!--  底部导航栏及签名导出  -->
    <bottomGuide
      v-if="isTrue"
      busiType="103"
      exportMethod="get"
      methodGetPageType="exportSettle"
      :approvalStatus="
        ['5', '22'].includes(settlementForm.settlementStatus)
          ? 'approvaled'
          : ''
      "
      :curPageId="$route.params.id"
      :businessCode="businessCode"
      @handleBack="handleBack"
    >
      <template slot="start">
        <li>
          <el-button
            v-if="
              !isApproval &&
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="openReturnDialog"
            >退回供应商
          </el-button>
        </li>
        <li>
          <el-button
            v-if="
              !isApproval &&
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="submitSettlement"
            >保存并提交
          </el-button>
        </li>
      </template>
    </bottomGuide>

    <returnDialog ref="returnDialog" @getValue="getValue" />
  </div>
</template>

<script>
import jsList from "../js";
import baseInfoCheck from "../components/baseInfoCheck";
import financeInfoCheck from "../components/financeInfoCheck";
import purchaseListCheck from "../components/purchaseListCheck";
import {
  getSettlementById,
  sendBackSupplierSettlement,
  submitSettlement
} from "../api/settlement-approval";
import fileInfo from "@/basa/components/public/uploadInfo3";
import returnDialog from "@/app/settlement-management/settlement-maintenance-approval/components/returnDialog";
import publicComponent from "@/basa/components/public";

export default {
  // mixins: [Mixin],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    fileInfo,
    baseInfoCheck,
    financeInfoCheck,
    purchaseListCheck,
    approvalReadRecord: publicComponent.approvalRecord,
    returnDialog,
    bottomGuide: publicComponent.bottomGuide
  },
  data() {
    return {
      businessCode: "",
      breadUrl: "",
      approving: "",
      activities: [],
      settlementForm: {
        pcConcId: "", // 基础合同id
        scConcId: "", // 结算申请单id
        materialName: "", // 合同名称
        materialCode: "", // 合同编号
        partyAName: "", // 合同甲方
        partyBId: "", // 合同乙方id
        partyBName: "", // 合同乙方
        materialName1: "", //供应商
        taxRatePercent: "", // 税率
        nowTotalContractPriceIncludeTax: "", // 合同金额（含税）
        settleTotalAmtIncludeTax: "", // 开累结算金额（含税）
        payedTotalAmtIncludeTax: "", // 开累支付金额
        settleTotalUnpaidAmt: "", // 开累结算未支付金额
        contractBalance: "", // 合同余额（含税）
        settlementNum: "", // 结算单编号
        settlementPeriod: "", // 结算期次
        currentSettlePayAmtIncludeTax: "", // 本期支付金额
        currentSettleAmtIncludeTax: "", // 本期结算金额（含税）
        currentSettleUnpayAmtIncludeTax: "", // 本期结算未支付金额（含税）
        paymentNum: "", // 支付单编号
        compiler: "", // 编制人
        compilerId: "", // 编制人id
        paymentApplyDate: "", // 支付申请日期
        remark: "" // 备注
      },
      fileList: [],
      jsList,
      breadcrumbLastItem: "物资合同",
      activeName: "first",
      isTrue: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      myId: "",
      tabBtn: [
        { label: "基本信息", value: "baseInfo" },
        { label: "财务信息", value: "financeInfo" },
        { label: "采购清单", value: "purchaseList" }
      ],
      summaryArr: ["subContractorsName"],
      tableTheadOptions: [
        {
          label: "合同编号",
          prop: "subContractName",
          width1: 120
        },
        {
          label: "合同名称",
          prop: "subContractorsName"
        }
      ],
      oneLineTableData: [
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 }
      ],
      arr1: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" },
        { id: 3, name: "cc" }
      ],
      arr2: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" }
      ],
      a: [],
      settlementList: [],
      approvingType: {
        1: "approving", // 审批中
        2: "withdrawn", // 已撤回
        3: "approvaled", // 审批通过
        4: "sendback", // 审批退回
        5: "unapproval" // 审批不通过
      },
      approvingStatus: true // 审批状态展示
    };
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  computed: {
    isApproval() {
      return this.$route.query.type == "approval";
    }
  },
  created() {
    let a = [...this.arr1];
    for (let i = 0; i < this.arr1.length; i++) {
      let flag = false;
      for (let j = 0; j < this.arr2.length; j++) {
        if (this.arr1[i].id === this.arr2[j].id) flag = true;
      }
      if (flag)
        a.splice(
          a.findIndex(_ => _.id === this.arr1[i].id),
          1
        );
    }
    this.myId = this.$route.params.id;
    this.breadUrl =
      sessionStorage.getItem("fromPath") ||
      "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all";
  },
  activated() {
    this.myId = this.$route.params.id;
    this.activeName = "first";
    this.init();
  },

  beforeRouteLeave(to,from,next) {
    // this.nextIsTrue();
    this.isTrue = false;
    next();
  },
  deactivated() {
    // this.nextIsTrue();
    this.isTrue = false;
  },
  methods: {
    init() {
      const data = {
        ids: [this.myId],
        isShowWorkflow: true,
        isShowPageLoading: true,
        loadingMessage: "加载中,请稍等..."
      };
      getSettlementById(data)
        .then(res => {
          this.businessCode = res.data.data.settlement.settlementCode;
          this.approving = res.data.data.settlement.approvalStatus;
          this.settlementForm = res.data.data.settlement;
          this.settlementList = res.data.data.settlementList;
          this.settlementList.map(item => {
            if (
              item.categoryCode &&
              (item.categoryCode.substr(0, 4) == "1305" ||
                item.categoryCode.substr(0, 4) == "1306" ||
                item.categoryCode.substr(0, 4) == "1307" ||
                item.categoryCode.substr(0, 4) == "1308" ||
                item.categoryCode.substr(0, 4) == "1309" ||
                item.categoryCode.substr(0, 6) == "990103")
            ) {
              this.$set(item, "isCategories", 1);
              this.$set(item, "settlementCount", item.residualSettlementNumber);
            }
            item.unTransportCount = item.unTransportCount
              ? (+item.unTransportCount).toFixed(3)
              : "";
            item.orderCount = item.orderCount
              ? (+item.orderCount).toFixed(3)
              : item.orderNumber
              ? (+item.orderNumber).toFixed(3)
              : "";
            item.acceptCount = item.acceptCount
              ? (+item.acceptCount).toFixed(3)
              : "";
            item.settlementCount = item.settlementCount
              ? (+item.settlementCount).toFixed(3)
              : "";
            item.unitPriceWithTax = item.unitPriceWithTax
              ? (+item.unitPriceWithTax).toFixed(2)
              : "";
            item.unitPriceWithoutTax = item.unitPriceWithoutTax
              ? (+item.unitPriceWithoutTax).toFixed(2)
              : "";
            item.moneyWithTax = (+item.moneyWithTax).toFixed(2);
            item.moneyWithoutTax = (+item.moneyWithoutTax).toFixed(2);
          });
          res.data.data.gistFiles.map(e => {
            e.fileType = 51;
            e.fileTypeName = "结算依据";
          });
          res.data.data.otherFiles.map(e => {
            e.fileType = 52;
            e.fileTypeName = "其他";
          });
          this.fileList = [
            ...res.data.data.gistFiles,
            ...res.data.data.otherFiles
          ];
          this.fileList.sort(this.handleSort("sn"));
          // 审批icon
          this.activities = res.data.data.approvalRecords;
          this.activities.forEach(item => {
            if (item.operState === 0) {
              item.icon = "el-icon-time";
              item.color = "#F5A623";
            }
          });
          this.approving =
            this.approvingType[res.data.data.settlement.approvalStatus];
          this.approvingStatus = false;

          this.settlementForm.settlements =
            this.settlementForm.settlementStart +
            "到" +
            this.settlementForm.settlementEnd;
          this.$nextTick(() => {
            this.approvingStatus = true;
            this.$refs["financeInfo"].handleTable(
              this.settlementForm.approvalStatus
            );
            this.$refs["purchaseList"].showTableData =
              this.settlementList.filter(
                e =>
                  e.isMainInventory == 0 &&
                  e.isOtherCost == 0 &&
                  !e.isCategories
              );
          });

          this.isTrue = true;
        })
        .catch(e => {});
    },

    // 退回操作
    openReturnDialog() {
      this.$refs["returnDialog"].visibleDialog = true;
    },

    // 退回弹框确定调用接口
    getValue(val) {
      let params = {
        id: +this.$route.params.id,
        supplierSendBackReason: val,
        isShowPageLoading: true
      };
      sendBackSupplierSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: res.data.message
        });
        this.handleBack();
      });
    },

    // 保存并提交操作
    submitSettlement() {
      this.settlementForm.billSource = "10";
      let params = {
        settlement: this.settlementForm,
        settlementList: this.settlementList,
        gistUploadIds: this.handleFilesParams().gistUploadIds,
        otherUploadIds: this.handleFilesParams().otherUploadIds,
        isShowPageLoading: true
      };
      submitSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: "保存并提交成功"
        });
        this.handleBack();
      });
    },

    // 处理附件入参
    handleFilesParams() {
      let gistUploadIds = [],
        otherUploadIds = [];

      this.fileList.map((e, i) => {
        if (e.fileType == 51) {
          gistUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        } else {
          otherUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        }
      });
      return {
        gistUploadIds: gistUploadIds,
        otherUploadIds: otherUploadIds
      };
    },

    // sort 排序
    handleSort(property) {
      return function (a, b) {
        return a[property] - b[property];
      };
    },

    handleClick(tab, event) {
      this.activeName = tab.name;
    },

    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all"
      );
    }
  }
};
</script>
<style scoped lang="scss">
.detail-info {
  width: calc(100% - 438px);
  min-height: calc(100vh - 260px);
  float: left;
  background: #fff;
  position: relative;
  padding: 20px;
}

.approval-read-record {
  margin-top: 0px;
}

.ccui-app-container-detail {
  background: none;
}

.detail-info-el-Label {
  position: absolute;
  width: 107px;
  right: 33px;
  top: 31px;
  z-index: 1;
}

/deep/ .el-tabs__customize {
  padding-bottom: 50px;
}
</style>
